package com.guoxue.action.front;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.auth.GXTokenSevice;
import com.guoxue.domain.BookConfigVo;
import com.guoxue.domain.DistrictVo;
import com.guoxue.domain.FollowsVo;
import com.guoxue.domain.IOSDeviceVo;
import com.guoxue.domain.LevelConfigVo;
import com.guoxue.domain.PersonPushVo;
import com.guoxue.domain.PlayerProgressVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.TotalInfoVo;
import com.guoxue.domain.UserVo;
import com.guoxue.service.IAlbumService;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.ICollectAndTransferService;
import com.guoxue.service.IDistrictService;
import com.guoxue.service.IExpertReadingService;
import com.guoxue.service.IFeedBackService;
import com.guoxue.service.IFollowsService;
import com.guoxue.service.IGiftListService;
import com.guoxue.service.IIOSDeviceService;
import com.guoxue.service.ILevelConfigService;
import com.guoxue.service.IPersonPushService;
import com.guoxue.service.IPlayerProgressService;
import com.guoxue.service.IReportService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.ITotalInfoService;
import com.guoxue.service.IUserCoinsService;
import com.guoxue.service.IUserCommentService;
import com.guoxue.service.IUserDistrictService;
import com.guoxue.service.IUserService;
import com.guoxue.util.LoadConfigProperties;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;


@Controller
@RequestMapping("User")
/**
 * 用户信息处理接口
 * 
 * @author young
 */
public class UserAction extends BaseAction {

	@Resource
	private IUserService userService;
	@Resource
	private ITapesRecordsService tapesService;
	@Resource
	private ITapesShareService shareService;
	@Resource
	private ITotalInfoService totalInfoService;
	@Resource
	private ILevelConfigService levelConfigService;
	@Resource
	private IPlayerProgressService playerProgressService;
	@Resource
	private IBookConfigService bookService;
	@Resource
	private IFollowsService followsService;
	@Resource
	private IUserCoinsService coinsService;
	@Resource
	private IUserCommentService commentService;
	@Resource
	private IReportService reportService;
	@Resource
	private IFeedBackService feedBackService;
	@Resource
	private IAlbumService albumService;
	@Resource
	private IDistrictService districtService;
	@Resource
	private GXTokenSevice gxTokenSevice;
	@Resource
	private OSSUtil oss;
	@Resource
	private ICollectAndTransferService collectAndTransferService;
	@Resource
	private IUserDistrictService userDistrictService;
	@Resource
	private IIOSDeviceService IOSDeviceService;
	@Resource
	private IGiftListService  iGiftListService;
	@Resource
	private IExpertReadingService expertServcie;
	@Resource
	private IPersonPushService personPushService;
	
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param account
	 * 			登录账号识别码快速登录时为设备号
	 * @param password
	 * 			用户键入密码
	 * @param type
	 * 			1：手机号登录
	 * 			2：QQ登录
	 * 			3：微信登录
	 * 			4：sina登录
	 * 			5：快速登录
	 *//*
		 * @RequestMapping(value = "/login")
		 * 
		 * @ResponseBody public JSON login(HttpServletRequest req,
		 * HttpServletResponse resp, String account, String password, Integer
		 * type) { account = account.trim(); try { if (isEmpty(account) || type
		 * == null) { return Message(ERROR, BAD_PARAM, null); } else { UserVo
		 * user = new UserVo(); if (type == 2 || type == 3 || type == 4 || type
		 * == 5) { // 非手机账号登录 user = userService.getUser(account); if (user !=
		 * null && user.getStatus() != 3) { if (user.getNickName() == null ||
		 * user.getSex() <= 0) { return Message(INFO_NOT_COMPLETE, "账号信息未完善",
		 * null); // 账号信息未完善，提示跳转创建角色 } else {
		 * req.getSession().setAttribute("user", user); JSONObject obj = new
		 * JSONObject(); obj.put("uid", user.getId()); obj.put("easemobPass",
		 * PasswordUtil.MD5Generator(user.getId()+"", user.getCreatedAt()));
		 * return Message(SUCCESS, "登录成功", obj); } } else { UserVo entiy = new
		 * UserVo(); entiy.setCreatedAt(OtherUtils.getCurrentDate());
		 * entiy.setStatus(1); if (type == 2) { // QQ用户
		 * entiy.setQqAccount(account); } else if (type == 3) { // 微信用户
		 * entiy.setWechatAccount(account); } else if (type == 4) { // sina用户
		 * entiy.setSinaAccount(account); } else { entiy.setIdentityId(account);
		 * entiy.setStatus(2); } userService.saveReturnKey(entiy); return
		 * Message(INFO_NOT_COMPLETE, "账号信息未完善", account); } } else if (type ==
		 * 1) { // 手机登录 if ("".equals(password) || password == null) { return
		 * Message(ERROR, BAD_PARAM, null); } user =
		 * userService.getUserByTel(account); if (user != null) { JSONObject obj
		 * = new JSONObject(); obj.put("uid", user.getId()); if
		 * (PasswordUtil.validPassword(user.getUserPassword(), password,
		 * user.getSalt())) { if (user.getNickName() == null || user.getSex() <=
		 * 0) { return Message(INFO_NOT_COMPLETE, "账号信息未完善", obj); }
		 * req.getSession().setAttribute("user", user); JSONObject json = new
		 * JSONObject(); json.put("uid", user.getId()); json.put("easemobPass",
		 * PasswordUtil.MD5Generator(user.getId()+"", user.getCreatedAt()));
		 * return Message(SUCCESS, "登录成功", json); } else if (user.getStatus() ==
		 * 3) { return Message(ERROR, "账号不正常", obj); } else { return
		 * Message(ERROR, PASSWORD_ERROR, obj); } } else { return Message(ERROR,
		 * NOT_EXIST, null); } } else { return Message(ERROR, "未知登录类型", null); }
		 * } } catch (Exception e) { return LoggerUtil.logInfo(e, ERROR); } }
		 */

	/**
	 * 创建社交账号以及游客注册新用户。
	 * @param req
	 * @param resp
	 * @param account
	 *           账号
	 * @param identityId
	 * 			设备号
	 * @param type
	 	 * 		1：手机号登录
	 * 			2：QQ登录
	 * 			3：微信登录
	 * 			4：sina登录
	 *//*
		 * @RequestMapping(value = "/createUserByAccount")
		 * 
		 * @ResponseBody public JSON creatUserByAccount(HttpServletRequest req,
		 * HttpServletResponse resp, String account, String identityId, Integer
		 * type) { try { if (type == null) { return Message(ERROR,
		 * BAD_PARAM,null); // 提示参数不全 } else { User user = new User();
		 * user.setIdentityId(identityId); user.setStatus(1); if (type == 5) {
		 * User entityA = userService.getUser(identityId); if (entityA != null)
		 * { // 当前手机游客身份存在 req.getSession().setAttribute("user", entityA);
		 * return Message(ALREADY_REG, GO_LOGIN,identityId); } else {
		 * user.setStatus(2); } } else { User entityB =
		 * userService.getUser(account); // 判断当前用户是否已存在，直接跳转登录？ if (entityB !=
		 * null) { req.getSession().setAttribute("user", entityB); return
		 * Message(ALREADY_REG, GO_LOGIN,account); } else { if (type == 2 &&
		 * !("".equals(account)) && account != null) { // QQ用户
		 * user.setQqAccount(account); } else if (type == 3 &&
		 * !("".equals(account)) && account != null) { // 微信用户
		 * user.setWechatAccount(account); } else if (type == 4 &&
		 * !("".equals(account)) && account != null) { // sina用户
		 * user.setSinaAccount(account); } else { return Message(ERROR,
		 * BAD_PARAM,null); } } } user.setCreatedAt(new Date());
		 * userService.saveUser(user); req.getSession().setAttribute("user",
		 * user); return Message(SUCCESS, "注册成功",
		 * account==null||"".equals(account)?identityId:account); } } catch
		 * (Exception e) { return LoggerUtil.logInfo(e, ERROR); }
		 * 
		 * }
		 */
	/**
	 * 获取个人资料
	 * @param req
	 * @param resp
	 * @param userId 用户id
	 * @return
	 */
	@RequestMapping("/getPersonalInfo")
	@ResponseBody
	public JSON getPersonalInfo(HttpServletRequest req, HttpServletResponse resp, Integer userId){
		if (userId==null){
			return Message(ERROR, "未提交用户id", null);
		}
		UserVo user = userService.getUserByKey(userId);
		JSONObject obj = new JSONObject();
		if (user!=null){
			PlayerProgressVo progress = playerProgressService.getPlayerProgressByUid(user.getId());
			// 获取对应下一级所需经验
			 List<LevelConfigVo> levels = new ArrayList<LevelConfigVo>(LoadConfigProperties.levelConfigMap.values());
			 int leve = 1;
			 int CurExp =0;
			 if (progress!=null){
				 CurExp = progress.getExp();
			 }
			
			 for(int x=0;x<levels.size();x++){
				 if(CurExp-levels.get(x).getExp()<0){
					 leve = x;
					 break;
				 }
				 CurExp = CurExp - levels.get(x).getExp();
			 }
			int nextlevelExp = LoadConfigProperties.levelConfigMap.get(leve+1).getExp(); //获取下一级所需经验;
			obj.put("personSignature", user.getPersonSignature());
			obj.put("sex", user.getSex());
			int d = 0;
			DistrictVo dst = new DistrictVo();
			d = user.getDistrict();
			if (d==0){
				obj.put("district", dst);
			}
			dst = districtService.getDistrictByKey(d);
			obj.put("district", dst);
			obj.put("headUrl",isEmpty(user.getImgUrl())?null:oss.getUrl(bucket, user.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
			obj.put("nickName", user.getNickName());
			obj.put("userTel", isEmpty(user.getUserTel())?"0":user.getUserTel());
			obj.put("exp",CurExp);
			obj.put("nextExp", nextlevelExp);
			obj.put("level", leve);
			int c = followsService.getFollowsCount(userId);
			int b = followsService.getBlackCount(userId);
			int m = followsService.getMyFollowsCount(userId);
			obj.put("blacker", b);
			obj.put("followed", c);
			obj.put("follows", m);
			obj.put("sina", isEmpty(user.getSinaAccount())?"0":"1");
			obj.put("qq", isEmpty(user.getQqAccount())?"0":"1");
			obj.put("wechat", isEmpty(user.getWechatAccount())?"0":"1");
		}
		return Message(SUCCESS, "获取信息成功", obj);
	}
	/**
	 * 获取个人页面信息
	 * @param req
	 * @param resp
	 * @param uid
	 * @return
	 */
	@RequestMapping("/getUserInfo")
	@ResponseBody
	public JSON getUserInfo(HttpServletRequest req, HttpServletResponse resp, Integer userId) {
		JSONObject obj = new JSONObject();
		if (userId == null) {
			return Message(ERROR, "未提交用户id", null);
		} else {
			UserVo user = userService.getUserByKey(userId);
			if (user == null) {
				return Message(ERROR, NOT_EXIST, null);
			} else {
				TotalInfoVo total = totalInfoService.getInfoByUid(user.getId());
				if (total == null) {
					total = new TotalInfoVo();
					total.setUid(user.getId());
					obj.put("follow", 0);
					obj.put("listened", 0);
					obj.put("follower", 0);
					totalInfoService.saveOrUpateInfo(total);
				} else {
					obj.put("follow", total.getFollow());
					obj.put("follower", total.getBeFollowed());
					obj.put("listened", total.getListened());
				}
				PlayerProgressVo player = playerProgressService.getPlayerProgressByUid(user.getId());// 获取当前用户等级进度信息
				int exp = 0;
				if (player == null) {
					player = new PlayerProgressVo();
					player.setUid(user.getId());
				} else {
					exp = player.getExp();
				}
				int leve = 1;
				 List<LevelConfigVo> levels = new ArrayList<LevelConfigVo>(LoadConfigProperties.levelConfigMap.values());
				 int CurExp =player.getExp();
				 for(int x=0;x<levels.size();x++){
					 if(CurExp-levels.get(x).getExp()<0){
						 leve = x;
						 break;
					 }
					 CurExp = CurExp - levels.get(x).getExp();
				 }
				int nextlevelExp = LoadConfigProperties.levelConfigMap.get(leve+1).getExp(); //获取下一级所需经验;
				obj.put("exp", CurExp);
				LevelConfigVo nextlevel = levelConfigService.getNextLevelByExp(exp);// 获取对应下一级所需经验
				obj.put("headUrl", isEmpty(user.getImgUrl())?null:oss.getUrl(bucket, user.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
				obj.put("userId", user.getId());
				
				obj.put("nextLevelExp", nextlevelExp);
				obj.put("level", leve);
				obj.put("userName", user.getNickName());
				obj.put("personSignature", user.getPersonSignature());
				//添加转发和收藏数量,还有我的作品数量
				//转发或者收藏(1.转发2.收藏)
				Long collectTotal = collectAndTransferService.getMyCollectAndTransferTotal(user.getId(),2);
				Long transferTotal = collectAndTransferService.getMyCollectAndTransferTotal(user.getId(),1);
				obj.put("transferTotal", transferTotal);
				obj.put("collectTotal", collectTotal);
				// 获取用户上传录音信息
				List<TapesRecordsVo> tapes = tapesService.findByUidAndStatus(user.getId(), 0);
				if (tapes.size() == 0) {// 若没有返回null
					obj.put("tapesTotal","0");
					return Message(SUCCESS, "获取用户信息成功", obj);
				} else {
					obj.put("tapesTotal",tapes.size());
					return Message(SUCCESS, "获取用户信息成功", obj);
				}
			}
		}
	}
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param userid
	 * 		用户id
	 * @param start
	 * 		开始第几个
	 * @param total
	 * 		需要查询几个
	 * @return
	 */
	@RequestMapping("getUserTapesInfo")
	@ResponseBody
	public JSON getUserTapes(HttpServletRequest req, HttpServletResponse resp, Integer userid, Integer start, Integer total, String date){
		if (start==null){
			return Message(ERROR, "未提交开始音频", null);
		}
		if (total==null){
			return Message(ERROR, "未提交音频数音频", null);
		}
		if (userid==null){
			return Message(ERROR, "未提交userid", null);
		}
		if (isEmpty(date)){
			return Message(ERROR, "未提交时间", null);
		}
		UserVo user = userService.getUserByKey(userid);
		JSONObject obj = new JSONObject();
		JSONArray tapesArray = new JSONArray();
		String path = req.getContextPath();
		String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
		List<TapesRecordsVo> tapes = new ArrayList<TapesRecordsVo>();
		if (date.equals("0")){
			tapes = tapesService.getTapesForCount(start,total,userid);
		} else {
			tapes = tapesService.getTapesForCounBytime(start,total,userid,date);
		}
		if(tapes==null||tapes.isEmpty()){
			return Message(ERROR, "没有更多了··", null);
		}
		for (TapesRecordsVo t : tapes) {// 获取对应录音点击量等数据
			JSONObject tapesInfo = new JSONObject();
			TapesShareVo share = shareService.getTapesShareByTid(t.getId(), 0);
			//TODO: 从静态资源获取数据 done
			BookConfigVo book = bookService.getBookByChapterId(Integer.parseInt(t.getFlag()));
			tapesInfo.put("nickName", user.getNickName());
			tapesInfo.put("headUrl", isEmpty(user.getImgUrl())?null:oss.getUrl(bucket, user.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
			tapesInfo.put("tapeId", t.getId());
			tapesInfo.put("top", t.getTop());
			tapesInfo.put("size", t.getSize());
			tapesInfo.put("tapesName", t.getTapes());
			tapesInfo.put("commitTime", t.getCommitTime());
			tapesInfo.put("chapterId", t.getFlag());
			tapesInfo.put("chapterName", t.getChapter());
			tapesInfo.put("belongBook", book.getBookName());
			tapesInfo.put("compent", isEmpty(t.getUserComment())?null:t.getUserComment());
			tapesInfo.put("shareUrl", basePath);
			tapesInfo.put("userId", user.getId());
			if (share != null) {
				tapesInfo.put("commentCount", share.getCommentCount());
				tapesInfo.put("gifts", share.getTotalGifts());
				tapesInfo.put("listened", share.getTotalListend());
				tapesInfo.put("shareCount", share.getShareCount());
			} else {// 若未查询到对应记录则生成一条对应记录存放数据库
				tapesInfo.put("commentCount", 0);
				tapesInfo.put("gifts", 0);
				tapesInfo.put("listened", 0);
				tapesInfo.put("shareCount", 0);
				share = new TapesShareVo();
				share.setTapesId(t.getId());
				shareService.saveTapesShare(share);
			}
			tapesArray.add(tapesInfo);
		}
		int c = tapesService.getTapesCounts(userid);
		obj.put("tapesTotal", c);
		obj.put("tapes", tapesArray);
		obj.put("time", OtherUtils.getCurrentDate());
		return Message(SUCCESS, "获取音频成功", obj);
	}

	/**
	 * 获取计数
	 * @param req
	 * @param resp
	 * @param uid
	 * 			用户id
	 * @return
	 */
	@RequestMapping("getMyCount")
	@ResponseBody
	public JSON getCount(HttpServletRequest req, HttpServletResponse resp,Integer userId){
		if (userId==null){
			return Message(ERROR, "未提交用户id", null);
		}
		int c = 0;
			c =	followsService.getFollowsCount(userId);
		int d = 0;
			d =	followsService.getBlackCount(userId);
		int e = 0 ;
			e =	followsService.getMyFollowsCount(userId);
		JSONObject obj = new JSONObject();
		obj.put("fens", c);
		obj.put("black", d);
		obj.put("follows", e);
		return Message(SUCCESS, "获取数据成功", obj);
	}
	
	/**
	 * 获取IOS设备唯一标识
	 * @param req
	 * @param resp
	 * @param uid 用户id
	 * @param identityId 设备唯一标识
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getDeviceToken")
	public JSON getDeviceToken(HttpServletRequest req, HttpServletResponse resp,Integer uid,String identityId){
		try{
			if (uid==null){
				return Message(ERROR, "未提交用户id", null);
			}
			if (identityId==null){
				return Message(ERROR, "未提交设备唯一标识", null);
			}
			IOSDeviceVo IOSDeviceVo = IOSDeviceService.getIOSDevice(uid);
			if(null == IOSDeviceVo){
				IOSDeviceVo = new IOSDeviceVo();
				IOSDeviceVo.setCreateTime(OtherUtils.getCurrentDate());
				IOSDeviceVo.setUid(uid);
				if(identityId.length() < 15){
					IOSDeviceVo.setType(2);
				}else{
					IOSDeviceVo.setDeviceToken(identityId);
					IOSDeviceVo.setType(1);
				}
			}else{
				if(identityId.length() > 15){
					IOSDeviceVo.setDeviceToken(identityId);
				}
			}
			IOSDeviceService.saveIOSDevice(IOSDeviceVo);
			return Message(SUCCESS, "开通推送消息成功", null);
		}catch(Exception e){
			return LoggerUtil.logInfo(e, "开通推送消息异常");
		}
	}
	
	
	/**
	 * 获取推送消息(除系统消息,每隔一段时请求一次)
	 * @param req
	 * @param resp
	 * @param uid 用户id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getPersonPush")
	public JSON getPersonPush(HttpServletRequest req, HttpServletResponse resp,Integer uid){
		try{
			if (uid==null){
				return Message(ERROR, "未提交用户id", null);
			}
			List<PersonPushVo> personPushList = personPushService.getPersonPushList();
			if(personPushList.size() > 0){
				PersonPushVo p = personPushList.get(0);//取最新一条数据
				List<FollowsVo> followsList = followsService.getFollowedList(Integer.valueOf(p.getUserId()));
				if(followsList.size() > 0){
					LinkedHashSet<Integer> uidList = new LinkedHashSet<Integer>();
					for(FollowsVo f:followsList){
						uidList.add(f.getFollowed());
					}
					if(uidList.contains(uid)){
						List<IOSDeviceVo> IOSDeviceList = IOSDeviceService.getIOSDeviceList(2);
						if(IOSDeviceList.contains(uid)){
							return Message(SUCCESS, "获取推送个人消息成功", p);
						}
					}else{
						return Message(SUCCESS, "获取推送个人消息成功", null);
					}
				}else{
					return Message(SUCCESS, "获取推送个人消息成功", null);
				}
			}
			return Message(SUCCESS, "获取推送个人消息成功", null);
		}catch(Exception e){
			return LoggerUtil.logInfo(e, "获取推送个人消息异常");
		}
	}
	
	/**
	 * 删除开启推送消息
	 * @param req
	 * @param resp
	 * @param uid 用户id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delPush")
	public JSON delPush(HttpServletRequest req, HttpServletResponse resp,Integer uid){
		try{
			if (uid==null){
				return Message(ERROR, "未提交用户id", null);
			}
			IOSDeviceService.delIOSDevice(uid);
			return Message(SUCCESS, "关闭推送消息成功", null);
		}catch(Exception e){
			return LoggerUtil.logInfo(e, "关闭推送消息异常");
		}
	}
	
}
